/*
* @Author: sam
* @Date:   2017-10-11 13:49:59
* @Last Modified by:   sam
* @Last Modified time: 2017-10-30 12:23:11
*/
var Utils = {
	geoData : '_geoData',
	setTitle : function(name){
		document.title = name;
	},
	getParams : function(){
		var search = location.search,obj = {},arr,member;
		var parmas;
		if(search === ""){
			return obj;
		}else{
			parmas = search.replace("?","");
			arr = parmas.split("&");
			for(var i in arr){
				var member = arr[i].split('=');
				obj[member[0].toLowerCase()] = encodeURI(member[1].toLowerCase());
			}
			//console.log(JSON.stringify(obj));
			return obj;
		}
	},
	getTrafficUrl : function(obj,type){
		var url,_device = "";
		var urls = {
			'baidu' : {
				'weixin' : 'http://api.map.baidu.com/direction?',
				'web' : 'http://api.map.baidu.com/direction?',
				'ios' : 'baidumap://map/direction?',
				'android' : 'baidumap://map/direction?'
			},
			'gaode' : {
				'weixin' : 'http://uri.amap.com/navigation?',
				'web' : 'http://uri.amap.com/navigation?',
				'ios' : 'iosamap://path?',
				'android' : 'amapuri://route/plan/?'
			}
		};

		obj.lng = obj.point.lng;
		obj.lat = obj.point.lat;
		obj.name = obj.address.province + obj.address.city + obj.address.street;
		obj.region = obj.address.city;

		if(device.mobile() === true){
			if(/micromessenger/.test(navigator.userAgent.toLowerCase())){
				_device = 'weixin';
			}else{
				if(device.ios() === true && device.iphone() === true){
					_device = 'ios';
				}
				if(device.android() === true){
					_device = 'android';
				}
			}

		}
		if(device.desktop() === true){
			_device = 'web';
		}
		url = urls[type][_device];

		return returnUrl(url,obj,type,_device);

		//返回url
		function returnUrl(url,parmas,type,device){
			var _url;
			if(type === 'baidu'){
				if(device === "weixin" || device === "web"){
				 	_url = url +　
					"origin=latlng:" + parmas.lat + "," + parmas.lng + "|name:" + parmas.name +
					"&destination=latlng:" + parmas.dest_lat + "," + parmas.dest_lng + "|name:" + parmas.dest_name +
					"&mode=transit" +
					"&region=" + parmas.region +
					"&output=html";
				}else{
				 	_url = url +　
					"origin=latlng:" + parmas.lat + "," + parmas.lng + "|name:" + parmas.name +
					"&destination=latlng:" + parmas.dest_lat + "," + parmas.dest_lng + "|name:" + parmas.dest_name +
					"&mode=transit" +
					"&region=" + parmas.region +
					"&output=html";
				}
			 }

			if(type === 'gaode'){
				if(device === "weixin" || device === "web"){
					_url = url +　
					"from=" + parmas.lng + ',' + parmas.lat + ',' + parmas.name +
					"&to=" + parmas.dest_lng + ',' + parmas.dest_lat + ',' + parmas.dest_name +
					"&mode=bus" +
					"&policy=0" +
					"&coordinate=gaode" +
					"&callnative=0";
				}else{
			 		_url = url +
			 		"sname=" + parmas.name +
			 		//"&sid=BGVIS1" + 
			 		"&slat=" + parmas.lat +
			 		"&slon=" + parmas.lng +
			 		//"&did=BGVIS2" +
			 		"&dname=" + parmas.dest_name +
			 		"&dlat=" + parmas.dest_lat +
			 		"&dlon=" + parmas.dest_lng +
			 		"&dev=0" +
			 		"&t=1";
				}
			}
			return encodeURI(_url);
		}
	},
	//百度转高度坐标系
	bd09tobcj02 : function(lng,lat){
	   	var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
	    var x = lng - 0.0065;
	    var y = lat - 0.006;
	    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_PI);
	    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_PI);
	    var gg_lng = z * Math.cos(theta);
	    var gg_lat = z * Math.sin(theta);
	    return {
	    	"lng" : gg_lng,
	    	"lat" : gg_lat
	    };
	},
	//高德转百度坐标系
	gcj02tobd09 : function(lng,lat){
		var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
	    var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
	    var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
	    var bd_lng = z * Math.cos(theta) + 0.0065;
	    var bd_lat = z * Math.sin(theta) + 0.006;
	    return {
	    	"lng" : bd_lng,
	    	"lat" : bd_lat
	    };
	},
	changePoints : function(points){
		var new_points = [],that = this;
		for(var i in points){
			new_points.push(that.gcj02tobd09(points[i]['lng'],points[i]['lat']));
		}
		return new_points;
	},
	getGeoLocalData : function(type){
		return JSON.parse(this.getLocalStorage(type + this.geoData));
	},
	getGeoLocation : function(key){
		var geolocation = new BMap.Geolocation();
		var that = this;
		geolocation.getCurrentPosition(function (r) {
			var gdlnglat;
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            	that.setLocalStorage('baidu' + that.geoData,JSON.stringify(r));
            	//console.log(JSON.stringify(r));
            	gdlnglat = that.bd09tobcj02(r.point.lng,r.point.lat);
            	r.point.lng = gdlnglat.lng;
            	r.point.lat = gdlnglat.lat;
            	r.longitude = gdlnglat.lng;
            	r.latitude = gdlnglat.lat;
            	//console.log(JSON.stringify(r));
            	that.setLocalStorage('gaode' + that.geoData,JSON.stringify(r));
            }
        });
	},
	setLocalStorage : function(key,value){
		localStorage.setItem(key,value);
	},
	getLocalStorage : function(key){
		return localStorage.getItem(key);
	},
	ajax : function(opt){
        opt = opt || {};
        opt.type = opt.type.toUpperCase() || 'POST';
        opt.url = opt.url || '';
        opt.async = opt.async || true;
        opt.data = opt.data || null;
        opt.success = opt.success || function () {};
        opt.beforeSend = opt.beforeSend || function () {};
        opt.afterSend = opt.afterSend || function () {};
        var xmlHttp = null;
        if (XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        }else {
            xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        }
        var params = [];
        for (var key in opt.data){
            params.push(key + '=' + opt.data[key]);
        }
        var postData = params.join('&');
        opt.beforeSend();
        if (opt.type.toUpperCase() === 'POST') {
            xmlHttp.open(opt.type, opt.url, opt.async);
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
            xmlHttp.send(postData);
        }else if (opt.type.toUpperCase() === 'GET') {
            xmlHttp.open(opt.type, opt.url + '?' + postData, opt.async);
            xmlHttp.send(null);
        }else{

        }
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                opt.success(xmlHttp.responseText);
                opt.afterSend();
            }
        };
    },
    //打电话
    makeCall : function(dom){
    	var tel = dom.getAttribute('tel');
    	//console.log('tel:' + tel);
    	window.location.href = 'tel:' + tel;
    },
    color : function(){
    	var color = ["#f16c4d","#fbaf5a","#acd372","#39b778","#00bff3","#5573b7","#bc8cbf","#f16d7e","#ed008c","#652c91","#0054a5","#0072bc","#00aeef","#00a650","#8fc63d","#fff100","#f7941d","#ee1d24","#8fc63d","#81ca9d"];
    	return color;
    },
    indexedDB : function(){
    	var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
		var dbconfig = {
			dbname : "xiangtanH5_db",
			version : 1,
			db : null,
			store : "cityJson"
		};
    	var obj = {
    		openDB : function(dbname,version,fn,clearTag){
    			var that = this;
    			dbname = dbname || dbconfig.dbname;
    			version = version || dbconfig.version;
    			fn = (typeof fn === 'function') ? fn : function(){};
				var request = indexedDB.open(dbname,version);
			    request.onerror=function(e){
			        console.log("打开数据库失败:" + e.currentTarget.error.message);
			    };
			    request.onsuccess=function(e){
			        dbconfig.db=e.target.result;
			        console.log('成功建立并打开数据库:'+ dbname +' version:'+ version);
			        if(clearTag === true){
			        	that.clearDB(null,fn);
			        }else{
			        	fn();
			        }
			    };
			    request.onupgradeneeded = function(e) {
			    	dbconfig.db=e.target.result;
			        if (!dbconfig.db.objectStoreNames.contains(dbconfig.store)) {
			        	dbconfig.db.createObjectStore(dbconfig.store);
                    	console.log('成功建立对象存储空间：'+dbconfig.store);
			        }
			    };
    		},
    		addData : function(key,value,db){
    			db = db || dbconfig.db;
    			var transaction = db.transaction(dbconfig.store,'readwrite');
    			var store = transaction.objectStore(dbconfig.store);
    			var request = store.put(value,key);
				request.onerror = function(){
                    console.error('add添加数据库中已有该数据');
                };
                request.onsuccess = function(){
                    console.log('add添加数据已存入数据库');
                };
    		},
    		findData : function(key,db,successFun,failFun){
    			db = db || dbconfig.db;
            	var transaction = db.transaction(dbconfig.store, "readwrite");
            	var store = transaction.objectStore(dbconfig.store);
            	var request = store.get(key);
                request.onsuccess = function(){
                    if(request.result === undefined){
                    	failFun();
                    }else{
                    	successFun(request.result);
                    }
                };
    		},
    		clearDB : function(db,fn){
    			var that = this;
    			db = db || dbconfig.db;
	            var request = db.transaction(dbconfig.store, "readwrite").objectStore(dbconfig.store).clear();
	            request.onsuccess = function() {
	            	fn();
	                console.log('清除成功');
	            };
    		},
    		deleteDB:function(){
    			indexedDB.deleteDatabase(dbconfig.dbname);
    		}
    	};

    	if(!indexedDB){
    		console.log("数据库不支持indexedDB");
    		return false;
    	}else{
    		return obj;
    	}
    }
};